#include "convexhulltestview.h"
#include "ui_convexhulltestview.h"
#include <vector>
#include "convexhull.h"
#include <QPainter>
#include <QMouseEvent>
#include "point.h"
namespace
{
typedef std::vector<Point *> PointArray;
}
ConvexHullTestView::ConvexHullTestView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConvexHullTestView)
{
    ui->setupUi(this);
}

ConvexHullTestView::~ConvexHullTestView()
{
    delete ui;
    ClearPoints();
}

void ConvexHullTestView::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::blue);

    Point *p;
    PointArray::iterator it = points_.begin();
    for(;it!= points_.end();++it)
    {
        p = *it;
        painter.drawEllipse(p->x() -2,p->y() - 2,4,4);
    }

    painter.setPen(QColor::fromRgb(255,0,255));
    QPainterPath path;

    it = convex_hull_.begin();

    if(it == convex_hull_.end())
        return;

    p = *it;
    path.moveTo(p->x(),p->y());
    painter.drawEllipse(p->x() -2,p->y() - 2,4,4);
    for(;it!= convex_hull_.end();++it)
    {
        p = *it;
        path.lineTo(p->x(),p->y());
        painter.drawEllipse(p->x() -2,p->y() - 2,4,4);
    }
    it = convex_hull_.begin();
    p = *it;
    path.lineTo(p->x(),p->y());
    painter.strokePath(path,QPen(Qt::red));
}

void ConvexHullTestView::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
    {
        //ClearConvexHull();
        convex_hull_.clear();
        this->convex_hull_ = ConvexHull::BuildConvexHull(points_);
        this->repaint();
    }
    else
    {
        Point *p = new Point(event->x(),event->y());
        points_.push_back(p);
        this->repaint();
    }
}

void ConvexHullTestView::ClearPoints()
{
    for(PointArray::iterator it = points_.begin();it!= points_.end();++it)
    {
        delete *it;
    }
    points_.clear();
}
